package shayu.auth.controller;

import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.TypeReference;
import dm.jdbc.util.StringUtil;
import io.renren.common.constant.AuthServerConstant;
import io.renren.common.exception.BizCodeEnume;
import io.renren.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import shayu.auth.feign.MemberFeignService;
import shayu.auth.feign.ThirdPartFeignService;
import shayu.auth.vo.UserLoginVo;
import shayu.auth.vo.UserRegistVo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static io.renren.common.constant.AuthServerConstant.LOGIN_USER;


@Controller
public class LoginController {

    @Autowired
    private ThirdPartFeignService thirdPartFeignService;

    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    // 注册服务
    @RequestMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone) {
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtil.isEmpty(redisCode)) {
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - 1 < 60000) {
                // 60秒之内不能在发
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(), BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }

        // 2. 验证码的再次校验，redis存key-phone value-code sms:code :手机号->验证码
        String code = UUID.randomUUID().toString().substring(0, 4);
        String substring=code+"_"+System.currentTimeMillis();

        // redis 缓存验证码  防止同一个phone在60秒可以再次发送验证码
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, substring, 10, TimeUnit.MINUTES);
        thirdPartFeignService.sendCode(phone, code);

        return R.ok();
    }

    // 登录服务
    @PostMapping("/login")
    public String login(@RequestBody UserLoginVo vo,
                        RedirectAttributes requestAttribute,
                        HttpSession session){
        // 远程登录
        R r = memberFeignService.login(vo);
        if(r.getCode()==0){
            // 成功
            session.setAttribute("data", LOGIN_USER);
            return "redirect:localhost:8060/login.html";
        }else{
            HashMap<String, String> errors = new HashMap<>();
            errors.put("msg",r.getData(new TypeReference<String>(){}));
            requestAttribute.addAttribute("errors",errors);
            return "redirect:localhost:8060/index/html";
        }
    }

    /**
     * 模拟重定向携带数据
     *
     * @param vo
     * @param result
     * @param redirectAttributes
     * @return
     */

    @PostMapping("/register")
    public String register(@Valid UserRegistVo vo, BindingResult result,
                         RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            // model.addAttribute("errors',errors)
            redirectAttributes.addFlashAttribute("errors", errors);
            // Request method 'Post' not supported
            // 用户注册 -> /regist[post]-->转发/ reg.html (路径映射默认都是get方法访问的)

            // 注册失败就重新进去注册页
            return "redirect:localhost:8060/reg.html";
        }

        // 1.校验验证码
        String code = vo.getCode();
        String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());

        if (!StringUtil.isEmpty(code)) {
            if (code.equals(s.split("_"))) {
                // 删除验证码
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                // // 验证码通过 真正注册调用远程服务进行注册
                R r = memberFeignService.register(vo);
                // 成功
                if (r.getCode() == 0) {
                    return "redirect:localhost:8054/login.html";
                } else {
                    HashMap<String, String> errors = new HashMap<>();
                    errors.put("msg", r.getData(new TypeReference<String>() {
                    }));
                    redirectAttributes.addFlashAttribute("errors", errors);
                    return "redirect:localhost:8060/reg.html";
                }
            } else {
                HashMap<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("msg", "验证码错误");
                // 用户注册 -> /regist[post] ----> 转发/reg.html(路径映射默认都是get方式访问的)
                // 校验出错 直接返回注册页
                return "redirect:localhost:8060/reg.html";
            }
        }else {
            HashMap<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("msg", "验证码错误");
            // 用户注册 -> /regist[post] ----> 转发/reg.html(路径映射默认都是get方式访问的)
            // 校验出错 直接返回注册页
            return "redirect:localhost:8060/reg.html";
        }
    }

    @GetMapping("/logout.html")
    public String logout(HttpServletRequest request) {
        request.getSession().removeAttribute(LOGIN_USER);
        request.getSession().invalidate();
        return "redirect:localhost:8054/login.html";
    }

    @GetMapping("/login.html")
    public String login(){

        return  "login.html";
    }

    @GetMapping("/reg.html")
    public String reg(){

        return  "reg.html";
    }
}

